package com.ask.langchain4j_springboot.controller;

import com.ask.langchain4j_springboot.service.MyAiService;
import dev.langchain4j.community.model.dashscope.QwenChatModel;
import dev.langchain4j.community.model.dashscope.QwenStreamingChatModel;
import dev.langchain4j.model.chat.ChatLanguageModel;
import dev.langchain4j.model.chat.response.ChatResponse;
import dev.langchain4j.model.chat.response.StreamingChatResponseHandler;
import io.swagger.v3.oas.annotations.Operation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Flux;

@RestController
@RequestMapping("/ai")
public class AiController {

    @Autowired
    ChatLanguageModel qwenChatModel;

    @Autowired
    QwenChatModel chatModel;

    @Autowired
    QwenStreamingChatModel streamingChatModel;

    @GetMapping("/chat")
    public String test(@RequestParam(defaultValue = "你是谁") String message) {
        String chat = chatModel.chat(message);
        return chat;
    }


    @GetMapping(value = "/stream_chat", produces = "text/stream;charset=UTF-8")
    public Flux<String> test1(@RequestParam(defaultValue = "你是谁") String message) {
        Flux<String> flux = Flux.create(sink -> {
            streamingChatModel.chat(message, new StreamingChatResponseHandler() {
                @Override
                public void onPartialResponse(String partialResponse) {
                    sink.next(partialResponse);  // 逐次返回部分响应
                }

                @Override
                public void onCompleteResponse(ChatResponse completeResponse) {
                    sink.complete();  // 完成整个响应流
                }

                @Override
                public void onError(Throwable error) {
                    sink.error(error);  // 异常处理
                }
            });
        });

        return flux;
    }

    @Autowired
    private MyAiService myAiService;
    @GetMapping("/memoryId_store_chat")
    @Operation(summary = "aiService接口")
    public String aiService(@RequestParam(defaultValue = "我是谁") String message, Integer userId) {
        return myAiService.chat(userId.toString(), message);
    }


}